import { reqGetDepartment, reqGetDoctors, reqGetSchedule } from '@/api/hospital/hospitalList';
import { BookingScheduleList, DepartmentItems, DoctorItem, DoctorsResponse } from '@/api/hospital/model/hospitalList';
import { Button, Card, Col, Pagination, Row, Tag, message } from 'antd'
import Table, { ColumnsType } from 'antd/lib/table';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { Key, useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom';

export default function HospitalSchedule() {
  //树状结构的数据
  const treeData: DataNode[] = [
    {
      title: 'parent 1',
      key: '0-0',
      children: [
        {
          title: 'parent 1-0',
          key: '0-0-0',
          disabled: true,
          children: [
            {
              title: 'leaf',
              key: '0-0-0-0',
              disableCheckbox: true,
            },
            {
              title: 'leaf',
              key: '0-0-0-1',
            },
          ],
        },
        {
          title: 'parent 1-1',
          key: '0-0-1',
          children: [{ title: <span style={{ color: '#1890ff' }}>sss</span>, key: '0-0-1-0' }],
        },
      ],
    },
  ];
  //表格数据
  let data: DoctorItem[] = [
    {
      "id": "645f30d8e7509f7cad13996e",
      "createTime": "2023-05-05 09:53:46",
      "updateTime": "2023-05-05 09:53:46",
      "isDeleted": 0,
      "param": {
        "dayOfWeek": "周日",
        "depname": "多发性硬化专科门诊",
        "hosname": "民航总医院"
      },
      "hoscode": "1000_8",
      "depcode": "200040878_8",
      "title": "医师",
      "docname": "张晓峰",
      "skill": "内分泌科常见病。",
      "workDate": "2023-05-28",
      "workTime": 0,
      "reservedNumber": 30,
      "availableNumber": 22,
      "amount": 100,
      "status": 1,
      "hosScheduleId": "112"
    },
    {
      "id": "645f30d8e7509f7cad13996f",
      "createTime": "2023-05-05 09:53:46",
      "updateTime": "2023-05-05 09:53:46",
      "isDeleted": 0,
      "param": {
        "dayOfWeek": "周日",
        "depname": "多发性硬化专科门诊",
        "hosname": "民航总医院"
      },
      "hoscode": "1000_8",
      "depcode": "200040878_8",
      "title": "副主任医师",
      "docname": "张红",
      "skill": "内分泌与代谢性疾病。",
      "workDate": "2023-05-28",
      "workTime": 1,
      "reservedNumber": 27,
      "availableNumber": 10,
      "amount": 100,
      "status": 1,
      "hosScheduleId": "114"
    }
  ];
  //定义表格结构
  let columns: ColumnsType<DoctorItem> = [
    {
      title: '序号',
      render: (a, b, index) => {
        return index + 1;
      }
    },
    {
      title: '职称',
      dataIndex: 'title'
    },
    {
      title: '号源时间',
      dataIndex: 'workDate'
    },
    {
      title: '总预约数',
      dataIndex: 'reservedNumber'
    },
    {
      title: '剩余预约数',
      dataIndex: 'availableNumber'
    },
    {
      title: '挂号费(元)',
      dataIndex: 'amount'
    },
    {
      title: '擅长技能',
      dataIndex: 'skill'
    },
  ];
  //创建一个 ref 容器
  // let div = useRef();
  //定义一个状态
  let [height, setHeight] = useState(200);
  //组件挂载完毕之后
  useEffect(() => {
    //计算左侧树状结构的高度
    let height = document.documentElement.clientHeight - 64 - 44 - 24 * 2 - 22 - 14;
    //更新状态
    setHeight(height);
    window.onresize = function () {
      //计算左侧树状结构的高度
      let height = document.documentElement.clientHeight - 64 - 44 - 24 * 2 - 22 - 14;
      //更新状态
      setHeight(height);
    }
  }, []);

  //获取 hoscode 参数
  let { hoscode } = useParams();
  //定义状态
  let [departments, setDepartments] = useState<DepartmentItems>([]);
  //定义展开科室的 id
  let [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //定义选中科室的状态
  let [depcode, setDepcode] = useState<string>('');
  let [depname, setDepname] = useState<string>('');
  //医生名称的状态
  let [hosname, setHosname] = useState<string>('');
  //当前排班日期的状态
  let [workDate, setWorkDate] = useState<string>('');
  //科室排班规则的状态
  let [schedules, setSchedules] = useState<BookingScheduleList[]>([]);
  //声明与分页相关的状态
  let [total, setTotal] = useState(0);
  let [current, setCurrent] = useState(1);
  let [pageSize, setPageSize] = useState(5);
  //声明排班医生的状态
  let [doctors, setDoctors] = useState<DoctorsResponse>([]);
  //组件挂载完毕之后发送请求
  useEffect(() => {
    let getDepartment = async () => {
      //获取所有的科室
      let result = await reqGetDepartment(hoscode as string);
      //为每一个一级科室添加 disabled 属性
      let departments = result.map(item => {
        return { ...item, disabled: true };
      });
      //更新状态
      setDepartments(departments);
      //设置展开的一级科室
      setExpandedKeys(result.map(item => item.depcode));
      //获取第一个一级科室中的第一个二级科室
      let depcode = (result[0].children as DepartmentItems)[0].depcode;
      let depname = (result[0].children as DepartmentItems)[0].depname;
      //更新当前的 depcode 状态
      setDepcode(depcode);
      //更新当前的科室名称状态
      setDepname(depname);
    }
    getDepartment();
  }, [])
  //声明函数
  let select = async (selectedKeys: Key[], info: any) => {
    //更新状态
    setDepcode(info.node.depcode);
    setDepname(info.node.depname);
  }

  //useEffect 简化代码
  useEffect(() => {
    let getSchedules = async () => {
      //判断状态的值
      if (depcode === '') return;
      try {
        setWorkDate('');
        //根据科室的 id 获取排班规则
        let schedules = await reqGetSchedule({ page: current, limit: pageSize, hoscode: hoscode as string, depcode: depcode })
        //更新科室排班规则的状态
        setSchedules(schedules.bookingScheduleList);
        //更新排班规则的总数
        setTotal(schedules.total);
        //更新医院名称的状态
        setHosname(schedules.baseMap.hosname);
        //获取第一天排班的日期
        let workDate = schedules.bookingScheduleList[0].workDate;
        //更新排班日期的状态
        setWorkDate(workDate);
      } catch (e) {
        setDoctors([]);
        
        message.error('请求失败~~');
      }
    }
    getSchedules();
  }, [depcode, depname, current, pageSize])


  useEffect(() => {
    let getDoctors = async () => {
      if(workDate === '') return;
      //获取某一天排班的医生
      let doctors = await reqGetDoctors({ hoscode: hoscode as string, depcode: depcode, workDate: workDate });
      //更新医生列表的状态
      setDoctors(doctors);
    }
    getDoctors();
  }, [workDate])
  return (
    <Card>
      {/* 路径导航 */}
      <p>选择：{hosname} / {depname} / {workDate}</p>
      {/* 主体内容 */}
      <Row gutter={20}>
        <Col span={5}>
          <div style={{ border: 'solid 1px #ddd', height: height, overflowY: 'scroll' }}>
            <Tree
              expandedKeys={expandedKeys}
              selectedKeys={[depcode]}
              defaultCheckedKeys={['0-0-0', '0-0-1']}
              fieldNames={{
                title: 'depname',
                key: 'depcode'
              }}

              treeData={departments as []}
              onSelect={select}
            />
          </div>
        </Col>
        <Col span={19}>
          {/* 排班日期信息 */}
          {
            schedules.map(item => {
              return <Tag
                onClick={async () => {
                  setWorkDate(item.workDate);
                }}
                color={workDate === item.workDate ? "green" : undefined} key={item.workDate}>
                <div>{item.workDate} {item.dayOfWeek}</div>
                <div>{item.availableNumber} / {item.reservedNumber}</div>
              </Tag>
            })
          }
          <div className="h-20"></div>
          {/* 分页 */}
          <Pagination current={current} total={total} pageSize={pageSize} onChange={(page: number, pageSize: number) => {
            setCurrent(page);
            setPageSize(pageSize);
          }}></Pagination>
          <div className="h-20"></div>
          {/* 表格 */}
          <Table bordered dataSource={doctors} columns={columns} pagination={false} rowKey={'id'}></Table>
          <div className="h-20"></div>
          {/* 返回按钮 */}
          <Button>返回</Button>
        </Col>
      </Row>
    </Card>
  )
}
